package org.pluslibs.commons.domplus;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlUtils {
	public static NodeList getNodesByXPath(Document destinationXml,String xPath) throws XPathExpressionException {
		XPath xpath = XPathFactory.newInstance().newXPath();
		XPathExpression expr = xpath.compile(xPath);
		Object result = expr.evaluate(destinationXml, XPathConstants.NODESET);
		NodeList nodes = (NodeList) result;
		return nodes;
	}
	public static Document getXmlDocument(String destination) throws SAXException, IOException, ParserConfigurationException {
		File file = new File(destination);
		DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document doc = builder.parse(file);
		return doc;
	}
	
	public static String nodeListTextToString(NodeList nodes) {
		String str="";
		for (int i = 0; i < nodes.getLength(); i++) {
			Element element = (Element) nodes.item(i);
			str+=element.getTextContent();
		}
		return str;
	}
	
	public static int getTagCount(Document destinationXml, String tag) {
		return destinationXml.getElementsByTagName(tag).getLength();
	}
	
	public static void doTransformation(String xsl_file, String source, String output)
			throws TransformerFactoryConfigurationError,
			TransformerConfigurationException, TransformerException,
			FileNotFoundException {
		TransformerFactory tFactory = TransformerFactory.newInstance();
		
		Transformer transformer = tFactory.newTransformer(new StreamSource(xsl_file));
		transformer.setOutputProperty(OutputKeys.METHOD, "html");
		transformer.transform(new StreamSource(source), new StreamResult(new FileOutputStream(output)));
	}

	
}
